<template>
    <div>
        <div
            class="contant"
            style="padding-top: 20px"
        >
            <div class="operatingArea">
                <div class="filter">
                    <div class="filter-item">

                        <el-date-picker
                            v-model="searchForm.time"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            style="width: 245px"
                        />
                    </div>
                    <div class="filter-item">
                        <el-button
                            type="primary"
                            @click="search"
                        >查询</el-button>
                        <el-button
                            type="primary"
                            @click="reset"
                        >重置</el-button>
                    </div>
                </div>
            </div>
            <el-table
                :data="tableData"
                style="width: 100%"
                highlight-current-row
                :cell-style="{ 'text-align': 'center' }"
                :header-cell-style="headerCellStyle"
                :row-class-name="tableRowClassName"
            >
                <el-table-column
                    prop="patrolTime"
                    label="巡查时间"
                    width="160"
                />
                <el-table-column
                    prop="patrolSummary"
                    label="被检查单位"
                >
                    <template #default="scope">
                        {{ scope.row.patrolDepName.join('，') }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="patrolPerson"
                    label="巡查参与人员"
                />
                <el-table-column
                    label="操作"
                    width="140"
                    fixed="right"
                >
                    <template #default="scope">
                        <el-button
                            type="primary"
                            :icon="View"
                            size="small"
                            @click="handleDetail(scope.$index, scope.row)"
                        >
                        </el-button>
                        <el-button
                            type="danger"
                            :icon="Delete"
                            size="small"
                            :disabled="isSupervisor"
                            style="margin-left: 4px;"
                            @click="handleDelete(scope.$index, scope.row)"
                        >
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="searchForm.pageNo"
                v-model:page-size="searchForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :page-sizes="[10, 20, 50, 100, 200]"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="equipmentPagination"
            />
        </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="1000px"
    >
        <div class="dialogContent">
            <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="100px"
                class="demo-ruleForm"
                :inline="true"
                :disabled="dialogType == 'detail'"
            >
                <div class="baseInfo sludgemodel">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                label="巡查时间"
                                prop="patrolTime"
                                class="demo-ruleForm-item"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="ruleForm.patrolTime"
                                    placeholder="巡查时间"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item
                                label="巡查目的"
                                prop="patrolPurpose"
                                class="demo-ruleForm-item"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="ruleForm.patrolPurpose"
                                    placeholder="巡查目的"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item
                                label="巡查参与人员"
                                prop="patrolPerson"
                                class="demo-ruleForm-item"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="ruleForm.patrolPerson"
                                    placeholder="巡查参与人员"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item
                                label="巡查总结"
                                prop="patrolSummary"
                                class="demo-ruleForm-item"
                                style="width: 100%;"
                            >
                                <el-input
                                    v-model="ruleForm.patrolSummary"
                                    placeholder="巡查总结"
                                    type="textarea"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <div class="carInfo sludgemodel">
                    <div class="modelTitle">
                        被检查污泥处置单位
                    </div>

                    <el-tabs
                        v-model="activeName"
                        class="demo-tabs"
                        @tab-click="handleClick"
                    >
                        <el-tab-pane
                            :label="item.depName"
                            :name="index"
                            v-for="(item, index) in ruleForm.patrolDepList"
                            :key="index"
                        >
                            <el-row>
                                <el-col :span="16">
                                    <el-form-item
                                        label="单位名称"
                                        prop="depName"
                                        class="demo-ruleForm-item"
                                        style="width: 100%;"
                                    >
                                        <el-input
                                            v-model="item.depName"
                                            placeholder="单位名称"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item
                                        label="巡查时间"
                                        prop="patrolDate"
                                        class="demo-ruleForm-item"
                                        style="width: 100%;"
                                    >
                                        <el-input
                                            v-model="item.patrolDate"
                                            placeholder="巡查时间"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col :span="5">
                                    <el-form-item
                                        label="现场图片"
                                        prop="sceneImageIds"
                                        class="demo-ruleForm-item"
                                        style="width: 100%;"
                                    >
                                        <div class="pictureList">
                                            <div
                                                class="pictureItem"
                                                v-for="(k, p) in item.imageIdsUrls"
                                                :key="p"
                                            >
                                                <div class="pic">
                                                    <el-image
                                                        style="width:100px;height:100px;"
                                                        :src="k"
                                                        :zoom-rate="1.2"
                                                        :max-scale="7"
                                                        :min-scale="0.2"
                                                        :preview-src-list="item.imageIdsUrls"
                                                        show-progress
                                                        :initial-index="p"
                                                        fit="cover"
                                                    >
                                                    </el-image>
                                                </div>
                                            </div>
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="exportList(id)"
                >导出</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<script setup>
import fileInfoHttp from "@/https/fileInfo.js";
import inspectionRecordHttp from "@/https/inspectionRecord.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import {
    Delete,
    View
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from 'moment';
import { onMounted, reactive, ref } from "vue";
const isSupervisor = ref(false)
const roleNames = ref(Storage.localGet("roleNames"))
if (roleNames.value.includes('supervisor')) {
    isSupervisor.value = true
}
const activeName = ref(0)
const searchForm = reactive({
    time: [moment().startOf('year').format('YYYY-MM-DD'), moment().endOf('month').format('YYYY-MM-DD')],
    startTime: moment().startOf('year').format('YYYY-MM-DD'),
    endTime: moment().endOf('month').format('YYYY-MM-DD'),
    pageNo: 1,
    pageSize: 10
})
const headerCellStyle = () => {
    let style = {
        background: '#f2f3f5',
        // color: '#fff',
        textAlign: 'center'
    }
    return style
}
const tableRowClassName = ({ row, rowIndex }) => {
    if ((rowIndex + 1) % 2 === 0) {
        // return 'warning-row'
    }
    return ''
}
const total = ref(0)
const tableData = ref([])
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
}
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
}
const reset = async () => {
    time = [moment().startOf('year').format('YYYY-MM-DD'), moment().endOf('month').format('YYYY-MM-DD')]
    startTime = moment().startOf('year').format('YYYY-MM-DD')
    endTime = moment().endOf('month').format('YYYY-MM-DD')
    searchForm.pageNo = 1
    searchForm.pageSize = 10
    search()
}
const search = async () => {
    let params = {
        startTime: searchForm.time[0] ? moment(searchForm.time[0]).format("YYYY-MM-DD") : '',
        endTime: searchForm.time[1] ? moment(searchForm.time[1]).format("YYYY-MM-DD") : '',
        pageNo: searchForm.pageNo,
        pageSize: searchForm.pageSize
    };
    const res = await inspectionRecordHttp.patrolPagePatrol(params)
    console.log(res.data)
    if (res.data.code == 200) {
        res.data.data.records.forEach(item => {
            let patrolDepNameList = []
            item.patrolDepList = JSON.parse(item.patrolDep)
            item.patrolDepList.forEach(async (m) => {
                patrolDepNameList.push(m.depName)
                m.imageIdsUrls = await getAllImageUrls(m.imageIds.split(','))
            })
            item.patrolDepName = patrolDepNameList
        })
        tableData.value = res.data.data.records
        console.log(tableData.value, 'tableData.value')
        total.value = res.data.data.total
    }
}
const getAllImageUrls = async (imgIds) => {
    const getImageUrl = imgIds.map(async (item, index) => {
        return await await fileInfoHttp.fileInfoGetById(item)
    })
    let imageUrlsList = []
    const results = await Promise.all(getImageUrl)
    results.forEach(item => {
        console.log(item.data.data.url)
        imageUrlsList.push(item.data.data.url)
    })
    return imageUrlsList
}

let ruleForm = ref({
    patrolTime: '',
    patrolPurpose: '',
    patrolDepList: [],
    patrolPerson: '',
    patrolPurpose: '',
    patrolSummary: '',
    patrolTime: '',
})

const currentRecord = ref({})
const dialogVisible = ref(false)
const dialogType = ref('')
const dialogTitle = ref('')
const handleDetail = (index, row) => {
    dialogVisible.value = true
    currentRecord.value = row
    dialogType.value = 'detail'
    dialogTitle.value = '详情'
    ruleForm.value = { ...row }
}
const handleDelete = async (index, row) => {
    ElMessageBox.confirm("确认删除该数据吗？", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(async () => {
            const { data } = await inspectionRecordHttp.patrolDeletePatrol(row)
            if (data.code == 200) {
                ElMessage({
                    message: "删除成功",
                    type: "success",
                });
                search()
            }
        })
}

const exportList = () => {
    inspectionRecordHttp.patrolExportPatrol(currentRecord.value).then((response) => {
        console.log(response);
        const content = response.data;
        const blob = new Blob([content], { type: "application/msword" });
        let fileName = `巡查记录`;
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
};
onMounted(() => {
    search()
})
</script>

<style scoped lang="less">
.contant {
    background: #fff;
    border-radius: 10px;
    box-sizing: border-box;
    padding-bottom: 16px;
    :deep(.el-tabs__nav) {
        padding: 0 20px !important;
    }
    :deep(.el-tabs__item) {
        font-weight: 400 !important;
        font-size: 14px;
    }
    :deep(.el-tabs__nav-wrap:after) {
        height: 1px;
    }
    :deep(.el-tab-pane) {
        padding: 0;
    }
    .operatingArea {
        padding: 0 10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }
    .addBtn {
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        margin-bottom: 10px;
    }
}
.dialogContent {
    .sludgemodel {
        // margin-bottom: 10px;
        .modelTitle {
            font-size: 16px;
            line-height: 18px;
            padding-left: 10px;
            border-left: 3px solid #38acf5;
            margin-bottom: 10px;
            font-weight: 500;
            .addCar {
                margin-left: 10px;
            }
        }
    }
    .carInfo {
        .carItem {
            padding: 0 14px;
            .carItemName {
                font-size: 12px;
                color: #666;
                line-height: 24px;
                border-bottom: 1px solid #eee;
                margin-bottom: 10px;
                position: relative;
                .deleteCar {
                    position: absolute;
                    right: 0;
                    top: 2px;
                    width: 14px;
                    height: 18px;
                    font-size: 10px;
                }
            }
        }
    }
    .hiddenAddPic {
        :deep(.el-upload--picture-card) {
            display: none;
        }
    }
}
.equipmentPagination {
    justify-content: center;
    margin-top: 10px;
}

.pictureList {
    display: flex;
    flex-direction: row;
    justify-content: left;
    .pictureItem {
        width: 120px;
        margin-right: 20px;
        .pic {
            width: 100px;
            height: 100px;
            font-size: 0;
            border-radius: 6px;
            overflow: hidden;
            margin: 0 auto;
        }
        .picName {
            text-align: center;
        }
        .image-slot {
            font-size: 12px;
            color: #999;
            text-align: center;
            line-height: 100px;
            border: 1px dashed #ccc;
            width: 98px;
            height: 98px;
            box-sizing: border-box;
            border-radius: 6px;
        }
    }
}
</style>
